﻿#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QCoreApplication>
#include <QString>
#include <QFile>
#include <QStandardItemModel>
#include <QStandardItem>
#include <QByteArray>
#include <QIODevice>
#include <QtXml/QDomNode>
#include <QtXml/QDomNodeList>
#include <QtXml/QDomDocument>
#include <QtXml/QDomElement>
#include <qicon.h>
#include <qfiledialog.h>


void appendNode(QStandardItem *items,QDomNode node,int iconIndex);
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->fileName->setText(QCoreApplication::applicationDirPath());
    ui->fileName->adjustSize();
    ui->fileName->setWordWrap(true);
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::on_selectFile_clicked()
{
	ui->treeView->setAutoScroll(true);
	QString filename,fulfilename;
	fulfilename = QFileDialog::getOpenFileName(
		0,
		"Select file",
		"\resource",
		"Allfile(*.*);;XMLfile(*.xml)",
		0,
		0);
	this->activateWindow();
	QFileInfo fi = QFileInfo(fulfilename);
	filename = fi.fileName();
    QDomDocument doc(filename);
    QFile file(fulfilename);
    if (!file.open(QIODevice::ReadOnly))
        return;
    if (!doc.setContent(&file)) {
        file.close();
        return;
    }
    file.close();
    QDomElement root = doc.documentElement();
    QStandardItemModel *model  = new QStandardItemModel(0,1,this);
	int iconIndex;
    QList<QStandardItem *> items;
    QDomNodeList list = root.childNodes();
    for(int i=0;i<list.count();i++) {
		iconIndex=0;
        QString tagname = list.at(i).toElement().tagName();
        QStandardItem *item= new QStandardItem(tagname);
        QString iconName = ":/debug/"+QString::number(iconIndex)+".png";
        iconIndex++;
        item->setIcon(QIcon(iconName));
		items.push_back(item);
		appendNode(items.at(i),list.at(i),iconIndex);
    }
	for(int j=0;j<items.count();j++)
	{
		model->appendRow(items.at(j));
	}
	model->setHeaderData(0,Qt::Horizontal,tr("TagName"));
    //model->appendRow(items);
    ui->treeView->setModel(model);
}

void appendNode(QStandardItem *items,QDomNode node,int iconIndex)
{
	if(node.hasChildNodes())
	{
		int tempIndex;
		QDomNodeList tempList = node.childNodes();
		if(tempList.count()>0)
		{
			for(int i = 0;i<tempList.count();i++)
			{
				QString tagname = tempList.at(i).toElement().tagName();
				if(tagname.trimmed()!="")
				{
					tempIndex = iconIndex;
					QStandardItem *item= new QStandardItem(tagname);
                    item->setIcon(QIcon(":/debug/"+QString::number(tempIndex).trimmed()+".png"));
                    tempIndex++;
					items->appendRow(item);
					appendNode(item,tempList.at(i),tempIndex);
				}
			}
		}
	}
}
